package com.module.overview.ui.historicalDataDetails

import android.view.View
import com.common.app.data.bean.CalendarDay
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.dialog.SelectCalendarDialog
import com.common.app.utls.TimeUtils.getPreviousDayTimestamp
import com.common.app.utls.TimeUtils.getTimeDateLong
import com.common.app.utls.TimeUtils.getWeekTimestamps
import com.common.app.utls.TimeUtils.getYearMonthDayHour3
import com.common.base.app.extras.no
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.yes
import com.common.base.app.fragment.BaseVMFragment
import com.common.base.utils.Page
import com.common.base.widget.animator.CustomAnimation1
import com.module.ble.utils.AllCardTypeConfig
import com.module.overview.R
import com.module.overview.databinding.OverviewFragmentHistoricalDataDetailsBinding
import com.module.overview.databinding.OverviewFragmentSubSummaryReportRecordBinding
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import java.util.Calendar

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/07/22
 *
 * 描述：
 *
 * 修订历史：
 *
 */
class HistoricalDataDetailsFragment :
    BaseVMFragment<OverviewFragmentHistoricalDataDetailsBinding, HistoricalDataDetailsViewModel>(), SelectCalendarDialog.OnSelectCalendarDialogListener {

    companion object {
        fun newInstance(mType: Int, mTitle: String): HistoricalDataDetailsFragment {
            val fragment = HistoricalDataDetailsFragment()
            fragment.mType = mType
            fragment.mTitle = mTitle
            return fragment
        }

    }

    private var mType = 0
    private var mTitle = "all"

    private var page: Page = Page()

    private var curWeekTimestamps = emptyArray<Pair<Long, Long>>()

    private val selectCalendarDialog by lazy { SelectCalendarDialog(requireActivity()) }

    // 检查当前周是否包含今天的时间戳
    val todayStartOfDay = Calendar.getInstance().apply {
        timeInMillis = getTimeDateLong()
        set(Calendar.HOUR_OF_DAY, 0)
        set(Calendar.MINUTE, 0)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
    }.timeInMillis


    private val mAdapter by lazy { HistoricalDataCardAdapter(mType) }

    override fun getPlaceholderView() = mViewBinding.placeHolderView

    override fun getViewModel() = HistoricalDataDetailsViewModel::class.java

    override fun getViewBinding() =
        OverviewFragmentHistoricalDataDetailsBinding.inflate(layoutInflater)

    override fun initViews() {
        super.initViews()

        mViewBinding.hrv.setItemViewCacheSize(30)
        getRefreshFooter()?.let { mViewBinding.pdView.setRefreshFooter(it) }

//        mViewBinding.pdView.setEnableFooterFollowWhenNoMoreData(true)
        mViewBinding.pdView.setEnableLoadMore(true)
//        mViewBinding.pdView.setEnableLoadMoreWhenContentNotFull(false)
        mViewBinding.pdView.setRefreshHeader(ClassicsHeader(requireActivity()))

        selectCalendarDialog.setShowGreyPoint(false)

        mAdapter.apply {
            adapterAnimation = CustomAnimation1()
            isAnimationFirstOnly = true
            addFooterView(layoutInflater.inflate(R.layout.base_rlv_margin_footer_tr_view50, null))
            mViewBinding.hrv.adapter = this
        }
    }

    override fun lazyInitData() {
        super.lazyInitData()
        initData()
    }

    override fun initEvents() {
        super.initEvents()
        setErrorRetryListener {
            lazyInitData()
        }

        mViewBinding.pdView.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                refreshLayout.layout.postDelayed({
                    finishPdView()
                }, 1000)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                finishPdView()
            }
        })

        mViewBinding.btnPrev.setOnClickListener(onClick = this)
        mViewBinding.btnNext.setOnClickListener(onClick = this)
        mViewBinding.tvTimeTitle.setOnClickListener(onClick = this)

        selectCalendarDialog.setListener(this)
    }


    override fun onClick(v: View?) {
        when (v) {
            mViewBinding.btnPrev -> {
                curWeekTimestamps.isNullOrEmpty().no {
                    curWeekTimestamps = getWeekTimestamps(getPreviousDayTimestamp(curWeekTimestamps.firstOrNull()?.first?:0))
                    mViewBinding.tvTimeTitle.text ="${getYearMonthDayHour3(curWeekTimestamps.firstOrNull()?.first?:0)} - ${getYearMonthDayHour3(curWeekTimestamps.lastOrNull()?.first?:0)}"
                    mViewBinding.btnNext.isEnabled = true
                    mViewBinding.btnNext.alpha = 1f
                    setList()
                }

                checkIsTheDay()
            }
            mViewBinding.btnNext -> {

                curWeekTimestamps.isNullOrEmpty().no {
                    curWeekTimestamps = getWeekTimestamps(getPreviousDayTimestamp(curWeekTimestamps.lastOrNull()?.first?:0, true))
                    mViewBinding.tvTimeTitle.text ="${getYearMonthDayHour3(curWeekTimestamps.firstOrNull()?.first?:0)} - ${getYearMonthDayHour3(curWeekTimestamps.lastOrNull()?.first?:0)}"
                    setList()
                }

                checkIsTheDay()
            }

            mViewBinding.tvTimeTitle -> selectCalendarDialog.show()
        }
    }

    private fun initData() {
        page.reset()

        curWeekTimestamps = getWeekTimestamps(getTimeDateLong())
        curWeekTimestamps.isNullOrEmpty().no {
            mViewBinding.tvTimeTitle.text ="${getYearMonthDayHour3(curWeekTimestamps.firstOrNull()?.first?:0)} - ${getYearMonthDayHour3(curWeekTimestamps.lastOrNull()?.first?:0)}"
        }
        checkIsTheDay()

        val temp = getDateString(0)
        selectCalendarDialog.setCurDay(temp)

        setList()
    }

    private fun setList(){
        val mList = mutableListOf<HistoryDetailsModel>()
        when (mTitle) {
            getString(R.string.common_sleep_hint) -> {
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_SLEEP_TOTAL_SCORE, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_SLEEP_SUB_SCORING, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_SLEEP_TOTAL_SLEEP_DURATION, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))

                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_SLEEP_WAKEFULNESS_DURATION, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_SLEEP_TOTAL_BED_REST_DURATION, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_SLEEP_RAPID_EYE_MOVEMENT_DURATION, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_SLEEP_LIGHT_SLEEP_DURATION, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_SLEEP_DEEP_SLEEP_DURATION, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_SLEEP_HR, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_SLEEP_BOXY, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_SLEEP_NAP_SLEEP_DURATION, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_SLEEP_SKIN_TEMPERATURE_DURATION, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_SLEEP_BREATHING_RATE, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
            }

            getString(R.string.common_activity_hint) -> {
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_ACTIVITY_TOTAL_SCORE, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_ACTIVITY_INTENSITY_DURATION, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_ACTIVITY_CONSUME, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_ACTIVITY_STANDING_DURATION, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_ACTIVITY_PORTS_RECORD, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
            }

            getString(R.string.common_pressure_hint) -> {
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_PRESSURE_THROUGHOUT_DAY, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_PRESSURE_RELIEF_DURATION, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
            }

            getString(R.string.common_signs_hint2) -> {
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_HD_SIGNS_HR, timePair= Pair(curWeekTimestamps.firstOrNull()?.first?:0, curWeekTimestamps.lastOrNull()?.second?:0)))
            }

            getString(R.string.common_exercise_hint) -> {

            }

            getString(R.string.common_period_hint) -> {

            }

        }
        mAdapter.setList(mList)
    }

    private fun finishPdView() {
        mViewBinding.pdView.finishRefresh()
        mViewBinding.pdView.finishLoadMore()
    }

    private fun checkIsTheDay(){

        // 如果当前周包含今天，则禁用下一周按钮
        // 检查todayStartOfDay是否在curWeekTimestamps的任何一个时间范围内
        val containsToday = curWeekTimestamps.any { (start, end) ->
            todayStartOfDay in start..end
        }

        containsToday.yes {
            mViewBinding.btnNext.isEnabled = false
            mViewBinding.btnNext.alpha = 0.4f
        }
    }

    private fun getDateString(dayOffset: Int): CalendarDay {
        val calendar = Calendar.getInstance()
        calendar.add(Calendar.DAY_OF_YEAR, dayOffset)

        val dateName = when (dayOffset) {
            0 -> getString(R.string.common_today_hint)
            else -> {
                val month = calendar.get(Calendar.MONTH) + 1
                val day = calendar.get(Calendar.DAY_OF_MONTH)
                "${month}月${day}日"
            }
        }

        return CalendarDay(
            year = calendar.get(Calendar.YEAR),
            month = calendar.get(Calendar.MONTH),
            day = calendar.get(Calendar.DAY_OF_MONTH),
            isCurrentMonth = false,
            isToday = dayOffset == 0,
            dateName = dateName,
            mCalendar = calendar
        )
    }

    override fun onSelectCalendarDialogClick(calendarDay: CalendarDay) {
        val temp = getWeekTimestamps(calendarDay.toCalendar().timeInMillis)
        if (temp.firstOrNull() == curWeekTimestamps.firstOrNull()) return
        curWeekTimestamps = temp
        curWeekTimestamps.isNullOrEmpty().no {
            mViewBinding.tvTimeTitle.text ="${getYearMonthDayHour3(curWeekTimestamps.firstOrNull()?.first?:0)} - ${getYearMonthDayHour3(curWeekTimestamps.lastOrNull()?.second?:0)}"
            setList()
        }
        checkIsTheDay()
    }
}